﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Collections.Specialized;
using System.Security.Cryptography.X509Certificates;

namespace DataAccess
{
    public partial class DataAccess
    {
        public DataAccessResult UpgradeDeployment(String SubscriptionID, String CertificatePath, String ServiceName, String DeploymentSlot, String mode, String PkgURL, String ConfigFile, String Label, String RoletoUpgrade)
        {
            DataAccessResult result = new DataAccessResult();
            WebResponse resp = null;
            try
            {

            FileStream fs = new FileStream(ConfigFile, FileMode.Open, FileAccess.Read);
            byte[] filebytes = new byte[fs.Length];
            fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
            string encodedData = Convert.ToBase64String(filebytes);
            String configData = encodedData;

            string requestUrl = "https://management.core.windows.net/" + SubscriptionID + "/services/hostedservices/"+ServiceName+"/deploymentslots/"+DeploymentSlot+"/?comp=upgrade";

            String RequestBodyFormat = @"<?xml version=""1.0"" encoding=""utf-8""?>
<UpgradeDeployment xmlns=""http://schemas.microsoft.com/windowsazure"">
  <Mode>{0}</Mode>
  <PackageUrl>{1}</PackageUrl>
  <Configuration>{2}</Configuration>
  <Label>{3}</Label>
  <RoleToUpgrade></RoleToUpgrade>
</UpgradeDeployment>";

                String requestBody = string.Format(RequestBodyFormat, mode, PkgURL, configData, Label);

                string ReturnBody = string.Empty;
                NameValueCollection RequestHeaders = new NameValueCollection();
                RequestHeaders.Add("x-ms-version", x_ms_version);
                X509Certificate cert = X509Certificate.CreateFromCertFile(CertificatePath);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
                request.Method = "POST";
                request.ClientCertificates.Add(cert);
                request.ContentType = "application/xml";
                //request.ContentLength = Encoding.UTF8.GetBytes(requestBody).Length;
                if (RequestHeaders != null)
                {
                    request.Headers.Add(RequestHeaders);
                }

                using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
                {
                    sw.Write(requestBody);
                    sw.Close();
                }
                resp = request.GetResponse();
                //RequestID = resp.Headers["x-ms-request-id"];
                 if (resp != null)
                {
                    HttpWebResponse httpResp = (HttpWebResponse)resp;
                    result.IsOperationSuccessful = httpResp.StatusCode.Equals(HttpStatusCode.Accepted);
                }
            }
            catch (WebException webEx)
            {
                result.IsOperationSuccessful = false;
                result.Error = webEx;
            }
            catch (Exception excep)
            {
                result.IsOperationSuccessful = false;
                result.Error = excep;
            }
            finally
            {
                
                if (resp != null) { resp.Close(); }
                resp = null;
            }
            return result;
        }
    }
}
